const http = require('http');
const https = require('https');
const express = require('express')
var bodyParser = require('body-parser');

const app = express()
const port = 3000

const SQLHelper = require('./SQLHelper')

app.use(express.static('www'))
// 解析body中间件
app.use(bodyParser.json({limit:'100mb'}));

// 微信登录
app.get('/wx/login', (req, res) => {

  let code = req.query.code
  let appid = 'wx710a811fca91e37b'
  let secret = 'ea44197bd58a4e0a11b3ec56a29a9b5d'
  // 模板语法``
  https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
    console.log('statusCode:', ret.statusCode);
    console.log('headers:', ret.headers);

    ret.on('data', (ret) => {
      ret = JSON.parse(ret.toString())
      let openid = ret.openid
      if(!openid){
        res.send({errorMsg: ret.errMsg || '获取openid错误'});
      }else{
        let queryMember = `select * from member where openId = '${openid}'`

        SQLHelper(queryMember).then(membersRet => {
          console.log(membersRet)
          if(membersRet.length){
            res.send(membersRet[0])
          }else{
            SQLHelper(`insert into member(openId) values('${openid}')`).then(newMember => {
              SQLHelper(queryMember).then(newMember => {
                res.send(newMember)
              })
            })
          }
        })
      }
    });

  }).on('error', (e) => {
    console.error(e);
    res.send({errorMsg:'获取openid错误'})
  });
  res.send('Hello World!')
})

app.put('/wx/member',(req,res) => {

  let userInfo = req.body
  SQLHelper(`
  update member
  set nickName = ${userInfo.nickName},avatarUrl=${userInfo.avatarUrl}
  where _id = ${userInfo._id}
  `).then(ret => {
    console.log(ret)
    res.send({})
  })

})
// 获取收获地址列表
app.get('/wx/address',(req,res) => {
  if(req.query.memberId) {
    SQLHelper(`select * from address where memberId = ${req.query.memberId}`).then(ret => {
      console.log(ret)
      res.send(ret)
    })
  }else {
      res.send({errorMsg:'请传入memberId'})
  }
  
})

// 新增收获地址
app.post('/wx/address',(req,res) => {
  if(req.body.memberId && req.body.receiver && req.body.phone && req.body.city) {
    SQLHelper(`insert into address(memberId,receiver,phone,city,area) values ('${req.body.memberId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}')`).then(ret => {
      console.log(ret)
      res.send(ret)
    })
  }else {
      res.send({errorMsg:'传入参数错误'})
  }
  
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

